package com.ningjingjing.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ningjingjing.model.Story;
import com.ningjingjing.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/api/story-detail.json")
public class StoryDetailApi extends AbsApiServlet {
    @Override
    protected Object doGetInner(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ServletException, IOException, APIException {
        int sid = Integer.parseInt(req.getParameter("sid"));
        Story story = new Story();
        story.sid = sid;
        story.audio = String.format("/get-audio?sid=%d", sid);

        // 统计故事播放量
        // 1. 更新 故事表的 count
        // 2. 更新 专辑表的 count
        try (Connection c = DBUtil.getConnection()) {
            // 1. 关闭 Connection 的自动 commit，因为默认是 true
            c.setAutoCommit(false);

            // 2. 更新 story 表
            try (PreparedStatement s = c.prepareStatement("UPDATE story SET count = count + 1 WHERE sid = ?")) {
                s.setInt(1, sid);
                s.executeUpdate();
            }

            // 3.0  根据 sid 先查询出 aid
            int aid;
            try (PreparedStatement s = c.prepareStatement("SELECT aid FROM story WHERE sid = ?")) {
                s.setInt(1, sid);
                try (ResultSet rs = s.executeQuery()) {
                    // TODO: 完全不考虑 sid 没有故事对应的情况了
                    rs.next();
                    aid = rs.getInt("aid");
                }
            }

            // 4. 更新 album 表
            try (PreparedStatement s = c.prepareStatement("UPDATE album SET count = count + 1 WHERE aid = ?")) {
                s.setInt(1, aid);
                s.executeUpdate();
            }

            // 5. 正式进行 commit
            c.commit();
        }

        try (Connection c = DBUtil.getConnection()) {
            String sql = "SELECT name FROM story WHERE sid = ?";
            try (PreparedStatement s = c.prepareStatement(sql)) {
                s.setInt(1, sid);

                try (ResultSet rs = s.executeQuery()) {
                    if (!rs.next()) {
                        throw new APIException("sid 对应的故事不存在");
                    }

                    story.name = rs.getString("name");
                    return story;
                }
            }
        }
    }
}
